package com.quanshu.exchange.ui.gui.message.mass_send;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.quanshu.exchange.R;
import com.quanshu.exchange.support.api.UserInterface;
import com.quanshu.exchange.support.db.UserDao;
import com.quanshu.exchange.support.entity.LabelEntity;
import com.quanshu.exchange.support.entity.UserEntity;
import com.quanshu.exchange.support.entity.tmp.TmpLabelEntity;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.CheckUtil;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.recycler.BaseViewHolder;
import com.quanshu.exchange.ui.base.recycler.DataDisplayer;
import com.quanshu.exchange.ui.base.recycler.LayoutWrapper;
import com.quanshu.exchange.ui.base.recycler.SingleAdapter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;

public class SelectLabelFriendsListActivity extends BaseActivity {

    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.ok_btn)
    ImageView okBtn;
    private SingleAdapter<TmpLabelEntity> adapter;
    private List<TmpLabelEntity> tmpLabelList = new ArrayList<>();
    private List<UserEntity> friendList;
    private HashMap<String, List<String>> beSelectedLabel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_label_list);
        ButterKnife.bind(this);
        initIntent();
        initView();
        initData();
        initListener();
    }

    private void initIntent() {
        beSelectedLabel = (HashMap<String, List<String>>) getIntent().getSerializableExtra("HashMap<String, List<String>>");
    }

    private void initView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new SingleAdapter<>(new DataDisplayer<TmpLabelEntity>(this, R.layout.item_select_friend_label_layout) {
            @Override
            public void bindData(BaseViewHolder holder, LayoutWrapper<TmpLabelEntity> wrapper, final TmpLabelEntity item, final int position) {
                holder.setText(R.id.label_name, item.getLabelName());
                holder.setText(R.id.label_member_num, "( " + item.getLabelMemberNum() + " )");
                holder.setText(R.id.label_member, item.getLabelMember());
                holder.setOnClickListener(view -> goLabelDetailActivity(item));
                ImageView checkBox = holder.getView(R.id.friend_check);
                if (CheckUtil.isValidate(beSelectedLabel)) {
                    Set keys = beSelectedLabel.keySet();
                    if (keys.contains(item.getLabelId())) {
                        checkBox.setSelected(true);
                    } else {
                        checkBox.setSelected(false);
                    }
                } else {
                    checkBox.setSelected(false);
                }
                checkBox.setOnClickListener(view -> {
                    boolean status = checkBox.isSelected();
                    if (beSelectedLabel == null) {
                        beSelectedLabel = new HashMap<>();
                    }
                    if (!status) {
                        String[] split = item.getLabelMemberId().split(",");
                        List<String> strings = new ArrayList<>();
                        if (split != null) {
                            strings.addAll(Arrays.asList(split));
                        }
                        beSelectedLabel.put(item.getLabelId(), strings);
                    } else {
                        beSelectedLabel.remove(item.getLabelId());
                    }
                    checkBox.setSelected(!status);
                    adapter.notifyDataSetChanged();
                });
            }
        });
        recyclerView.setAdapter(adapter);
    }

    private void goLabelDetailActivity(TmpLabelEntity item) {
        Intent intent = new Intent(this, LabelDetailActivity.class);
        intent.putExtra("TmpLabelEntity", item);
        if (CheckUtil.isValidate(beSelectedLabel)) {
            intent.putExtra("List<String>", (Serializable) beSelectedLabel.get(item.getLabelId()));
        }
        startActivityForResult(intent, 0x01);
    }

    private void initListener() {
        RxViewHelper.getInstance().clicks(back, aVoid -> finish());
        RxViewHelper.getInstance().clicks(okBtn, aVoid -> doClickOk());
    }

    private void doClickOk() {
        Intent intent = getIntent();
        if (CheckUtil.isValidate(beSelectedLabel)) {
            intent.putExtra("HashMap<String, List<String>>", beSelectedLabel);
        }
        setResult(RESULT_OK, intent);
        finish();
    }

    private void initData() {
        friendList = UserDao.getInstance().queryForAll();
        if (friendList == null) {
            friendList = new ArrayList<>();
        }
        NetClient.getInstance()
                .getNetService(UserInterface.class)
                .getFriendLabelList(AppUtils.getSignParams(currentUser.getMemberid()), currentUser.getMemberid())
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse<List<LabelEntity>>>() {
                    @Override
                    public void onSuccess(BaseResponse<List<LabelEntity>> response) {
                        formatList(response.getInfo());
                    }
                });
    }

    private void formatList(List<LabelEntity> labelList) {
        if (labelList == null || labelList.size() < 1) {
            return;
        }
        tmpLabelList.clear();
        TmpLabelEntity tmpLabelEntity;
        for (int i = 0; i < labelList.size(); i++) {
            tmpLabelEntity = new TmpLabelEntity();
            tmpLabelEntity.setLabelId(labelList.get(i).getId());
            tmpLabelEntity.setLabelName(labelList.get(i).getLabel_name());
            int z = 0;
            StringBuffer memberName = new StringBuffer();
            StringBuffer memberId = new StringBuffer();
            for (int j = 0; j < friendList.size(); j++) {
                if (labelList.get(i).getId().equals(friendList.get(j).getLabel_id())) {
                    z += 1;
                    String string = AppUtils.getUserName(friendList.get(j));
                    memberName.append(string);
                    memberId.append(friendList.get(j).getMemberid());
                    memberName.append(",");
                    memberId.append(",");
                }
            }
            tmpLabelEntity.setLabelMemberNum(z);
            tmpLabelEntity.setLabelMember(memberName.toString());
            tmpLabelEntity.setLabelMemberId(memberId.toString());
            tmpLabelList.add(tmpLabelEntity);
        }
        adapter.setData(tmpLabelList);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 0x01) {
                List<String> selectedUser = (List<String>) data.getSerializableExtra("List<String>");
                String label = data.getStringExtra("String");
                if (beSelectedLabel == null) {
                    beSelectedLabel = new HashMap<>();
                }
                if (CheckUtil.isValidate(selectedUser)) {
                    beSelectedLabel.put(label, selectedUser);
                } else {
                    beSelectedLabel.remove(label);
                }
                if (adapter != null) {
                    adapter.notifyDataSetChanged();
                }
            }
        }
    }
}
